// 等待
const PEDDING = 'pedding';
// 成功
const FULFILLED = 'fulfilled';
// 失败
const REJECTED = 'rejected';

function MyPromise(executor) {
  // this.state 代表Promise的状态
  this.state = PEDDING;
  // this.value是Promise的结果值
  this.value = null;
  // this.reason是Promise的失败原因
  this.reason = null;
  // this.onFulfilledCallbacks是一个数组，用来存放回调
  this.onFulfilledCallbacks = [];
  // this.onRejectedCallbacks是一个数组，用来存放失败的回调
  this.onRejectedCallbacks = [];

  // resolve reject
  const resolve = (value) => {
    if (this.state === PEDDING) {
      this.state = FULFILLED;
      this.value = value;
      this.onFulfilledCallbacks.forEach((cb) => {
        cb();
      });
    }
  };

  const reject = (reason) => {
    if (this.state === PEDDING) {
      this.state = REJECTED;
      this.reason = reason;
      this.onRejectedCallbacks.forEach((cb) => {
        cb();
      });
    }
  };
  try {
    executor(resolve, reject);
  } catch (reason) {
    reject(reason);
  }
}
MyPromise.prototype.then = function (
  onFulfilled = (value) => value,
  onRejected = (reson) => reson
) {
  // const self = this;
  // return new MyPromise((resolve, reject) => {
  //   handle.call(self, onFulfilled, onRejected, resolve, reject);
  // });
  switch (this.state) {
  case PEDDING:
    // 处理的是将所有的回调收集到一起
    this.onFulfilledCallbacks.push(() => {
      onFulfilled(this.value);
    });
    this.onRejectedCallbacks.push(() => {
      onRejected(this.reason);
    });
    break;
  case FULFILLED:
    onFulfilled(this.value);
    break;
  case REJECTED:
    onRejected(this.reason);
    break;
  default:
    console.log('default');
    break;
  }
  // return this;
};

const promise = new MyPromise((resolve, reject) => {
  console.log(1);
  resolve(2);
});
promise.then(res=>console.log(res)); 
console.log(3);
// 1 3 2